package pe.gob.proviasnac.app.utiles;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;

import org.apache.ibatis.session.SqlSession;

public class SecuenciaUtil {

	public static Integer obtenerSecuencia(String nombreTablaColumna, SqlSession session) {
		
		String[] param = nombreTablaColumna.split("-");
		
		Integer secuencia = null;
		Connection con = session.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			
			//Class.forName(driver);
			//con = DriverManager.getConnection("jdbc:mysql://"+host+":"+port+"/"+database+"", username, password);
			
			try {
				
				String sql = "select max(t."+param[1]+") + 1 as secuencia from "+param[0]+" t;";
				ps = con.prepareStatement(sql);
				rs = ps.executeQuery();

				while (rs.next()) {
					secuencia = rs.getInt(1);
					if(secuencia == 0){
						secuencia++;
					}
				}
				
			} catch (SQLException s) {
				secuencia = -1;
				System.out.println("SQL statement is not executed!");
			}finally{
				try {
					if(rs != null){rs.close();}
					if(ps != null){ps.close();}
					//if(con != null){con.close();}
				} catch (SQLException e) {
					e.printStackTrace();
				}		
			}
			
		} catch (Exception e) {
			secuencia = -1;
			e.printStackTrace();
		}
		return secuencia;
	}

}
